package com.feign;

import com.service.ISmsRedisService;
import com.util.Consts;
import com.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class SmsFeignApiClient implements SmsFeignApi {
    @Autowired
    private ISmsRedisService smsRedisService;
    @Override
    public JsonResult sendVerifyCode(String phone) {
        //短信发送
        //创建验证码
        String code = UUID.randomUUID().toString()
                .replaceAll("-", "")
                .substring(0, 4);
        //创建短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("您注册的短信验证码是：").append(code).append("，请在")
                .append(Consts.VERIFY_CODE_VAI_TIME)
                .append("分钟内使用");
        //假装短信已发送
        System.out.println(sb);
        //将短信验证码缓存redis
        smsRedisService.setVerifyCode(phone,code);
        return JsonResult.success();
    }

    @Override
    public JsonResult checkVerifyCode(String phone, String verifyCode) {
        //校验短信验证码是否正确
        String code = smsRedisService.getVerifyCode(phone);
        if (code == null || !verifyCode.equalsIgnoreCase(code)){
            throw new RuntimeException("验证码失效或错误");
        }
        return JsonResult.success(true);
    }
}
